package com.etalk.crm.controller.lesson;
import	java.util.Date;

import com.alibaba.fastjson.JSON;
import com.etalk.crm.pojo.CancelCourseRecord;
import com.etalk.crm.pojo.LessonResult;
import com.etalk.crm.pojo.StudentEvaluationResult;
import com.etalk.crm.service.LessonsService;
import com.etalk.crm.service.StudentInfoService;
import com.etalk.crm.service.UserService;
import com.etalk.crm.utils.PojoMapUtils;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jordan
 */
@Controller
@RequestMapping("/lesson")
public class LessonController {
    private static final Logger logger = LogManager.getLogger(LessonController.class);

    @Resource
    private LessonsService lessonsService;
    @Resource
    private UserService userService;
    @Resource
    private StudentInfoService studentInfoService;

    @Resource
    private HttpSession session;

    @Value("${interface.booked.courese.url}")
    String bookedUrl;

    /**
     * 学员课程列表
     * @param model 页面数据
     * @param personId 学员id
     * @param classStartTime 查询课程时间开始日期
     * @param classEndTime 查询课程时间结束日期
     * @param pageNum 页码
     * @param pageSize 每页记录数
     * @return 页面
     */
    @RequestMapping(value = "/student/list/{personId}",method = {RequestMethod.POST,RequestMethod.GET})
    public String searchLessonPageByPersonId(Model model, @PathVariable("personId") int personId, Integer classState,String classStartTime, String classEndTime,String tokenString, Integer pageNum, Integer pageSize){
        try {
            PageInfo<LessonResult> pageInfo=lessonsService.searchLessonPageByPersonId(personId,classState,classStartTime,classEndTime,pageNum,pageSize);
            model.addAttribute("pageInfo",pageInfo);
            model.addAttribute("personId",personId);
            model.addAttribute("classState",classState);
            model.addAttribute("classStartTime",classStartTime);
            model.addAttribute("classEndTime",classEndTime);
            model.addAttribute("pageSize",pageSize);
            model.addAttribute("tokenString",tokenString);
            model.addAttribute("bookedUrl",bookedUrl);
        } catch (ParseException e) {
            logger.error("查询日期格式转换错误：{}",e.getMessage(),e);
            model.addAttribute("errMsg",e.getMessage());
        }
        return "lesson/lesson_list_student";
    }

    @RequestMapping(value = "/list/page",method = {RequestMethod.POST,RequestMethod.GET})
    public String searchLessonPage(Model model, LessonResult record, String tokenString, Integer pageNum, Integer pageSize){

        PageInfo<LessonResult> pageInfo=lessonsService.searchLessonPage(record,pageNum,pageSize);
        model.addAttribute("pageInfo",pageInfo);
        model.addAllAttributes(PojoMapUtils.convert2Map(record));
        model.addAttribute("tokenString",tokenString);
        model.addAttribute("bookedUrl",bookedUrl);
        model.addAttribute("listSsc",userService.sscList());
        return "lesson/lesson_list";
    }

    @RequestMapping(value = "/change/init/{lessonId}",method = {RequestMethod.POST,RequestMethod.GET})
    public String changeLessonInfoByLessonId(Model model,@PathVariable("lessonId") Integer lessonId){
        LessonResult lessonResult=lessonsService.searchChangeLessonInfoByLessonId(lessonId);
        model.addAttribute("lessonInfo",lessonResult);
        model.addAttribute("teaSite",lessonsService.searchTeacherSiteList());
        model.addAttribute("teaLevel",lessonsService.searchTeacherLevelList());
        model.addAttribute("classWay",lessonsService.searchClassWayList());
        model.addAttribute("reason",lessonsService.searchLessonChangeReasonList());
        model.addAttribute("bookedUrl",bookedUrl);
        model.addAttribute("tokenString",studentInfoService.getStudentTokenString(lessonResult.getPersonId()));
        return "lesson/change_lesson_info";
    }

    @RequestMapping(value = "/return/class/{lessonId}",method = {RequestMethod.POST,RequestMethod.GET})
    public String returnClassByLessonId(Model model,@PathVariable("lessonId") Integer lessonId){
        LessonResult lessonResult=lessonsService.searchChangeLessonInfoByLessonId(lessonId);
        model.addAttribute("lessonInfo",lessonResult);
       /* model.addAttribute("teaSite",lessonsService.searchTeacherSiteList());
        model.addAttribute("teaLevel",lessonsService.searchTeacherLevelList());
        model.addAttribute("classWay",lessonsService.searchClassWayList());
        model.addAttribute("reason",lessonsService.searchLessonChangeReasonList());*/
        model.addAttribute("bookedUrl",bookedUrl);
        return "lesson/lesson_return_class";
    }

    /**
     * 获取取消课程原因列表
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/cancel/course/reason/list",produces = "application/json;charset=utf-8")
    public String getCancelCourseReasonList(){
        Map<String,Object> resultMap=new HashMap<>(2);
        resultMap.put("status",1);
        List<CancelCourseRecord> list=lessonsService.searchCancelCourseReasonList();
        resultMap.put("data",list);
        return JSON.toJSONString(resultMap);
    }

    @ResponseBody
    @PostMapping(value = "/change/course/reason/list",produces = "application/json;charset=utf-8")
    public String getChangeCourseReasonList(){
        Map<String,Object> resultMap=new HashMap<>(2);
        resultMap.put("status",1);
        List<Map<String,Object>> list=lessonsService.searchLessonChangeReasonList();
        resultMap.put("data",list);
        return JSON.toJSONString(resultMap);
    }

    @RequestMapping(value = "/student/evaluation/list",method = {RequestMethod.POST,RequestMethod.GET})
    public String searchLessonStudentEvaluationByPage(Model model, StudentEvaluationResult result, Integer pageNum, Integer pageSize){
        if (StringUtils.isEmpty(pageNum)){
            pageNum=1;
        }
        if (StringUtils.isEmpty(pageSize)){
            pageSize=15;
        }
        int roleId=Integer.parseInt(session.getAttribute("roleId").toString());
        List<Integer> list=new ArrayList<>();
        if (roleId==8) {
            list.add(Integer.parseInt(session.getAttribute("userid").toString()));
            result.setListSscId(list);
            model.addAttribute("cclist",userService.searchCcSelectList(list));
        }else if (roleId==2) {
            list.add(Integer.parseInt(session.getAttribute("userid").toString()));
            result.setListCcId(list);
            model.addAttribute("ssclist",userService.searchSscSelectList(list));
        }else {
            if (result.getListSscId()!=null){
                list.addAll(result.getListSscId());
            }
            model.addAttribute("ssclist",userService.searchSscSelectList(list));
            list.clear();
            if (result.getListCcId()!=null){
                list.addAll(result.getListCcId());
            }
            model.addAttribute("cclist",userService.searchCcSelectList(list));
        }

        PageInfo<StudentEvaluationResult> pageInfo=lessonsService.searchLessonStudentEvaluationByPage(result,pageNum,pageSize);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("pageNum",pageNum);
        model.addAttribute("pageSize",pageSize);
        model.addAllAttributes(PojoMapUtils.convert2Map(result));

        return "lesson/lesson_student_evaluation_list";
    }

    @ResponseBody
    @PostMapping(value = "/update/show/{lessonId}/{show}",produces = "application/json;charset=utf-8")
    public String updateLessonShow(@PathVariable("lessonId")int lessonId,@PathVariable("show")int show){
        Map<String,Object> resultMap=new HashMap<>(2);
        int num=lessonsService.updateLessonShowByLessonId(lessonId,show);
        resultMap.put("status",num);
        return JSON.toJSONString(resultMap);
    }

    /**
     * 查询老师空闲时间表
     * @param teacherLevel 老师级别id
     * @param startDate 查询日期
     * @param groupId 老师组id
     * @param teacherName 老师账号
     * @return
     */
    @RequestMapping(value = "/teacher/free/class",method = {RequestMethod.POST, RequestMethod.GET})
    public String getTeacherFreeClassTime(Model model,Integer teacherLevel, String startDate, Integer groupId, String teacherName){
        if (org.apache.commons.lang3.StringUtils.isEmpty(startDate)){
            startDate= DateFormatUtils.format(new Date(),"yyyy-MM-dd");
        }
        List<LessonResult> list=lessonsService.searchTeacherFreeClassTimeList(teacherLevel,startDate,groupId,teacherName);
        model.addAttribute("listFree",list);
        model.addAttribute("teacherLevel",teacherLevel);
        model.addAttribute("startDate",startDate);
        model.addAttribute("groupId",groupId);
        model.addAttribute("teacherName",teacherName);
        return "teacher/teacher_free_class_time";
    }

    /**
     * 老师完成课程后的评价信息
     * @param model 对象
     * @param lessonId 课程id
     * @return
     */
    @RequestMapping(value = "/course/evaluation/info/{lessonId}",method = {RequestMethod.GET})
    public String getCourseEvaluationInfo(Model model,@PathVariable("lessonId")int lessonId){
        model.addAttribute("comments",lessonsService.searchCourseCommentsInfo(lessonId));

        return "lesson/lesson_comment_info";
    }
}
